package qyWechat

import (
	"encoding/xml"
	"fmt"
	"net/http"
	"time"
	"ulcdkey/tool"
)

type defaultResponse struct {
	c Context
	w http.ResponseWriter
}

func (d defaultResponse) write(b []byte) (err error) {
	_, err = d.w.Write(b)
	return
}

func (d defaultResponse) send(data interface{}) (err error) {
	b, err := xml.Marshal(data)
	if err != nil {
		return err
	}
	b, err = d.c.Wechat().EncryptMsg(string(b), fmt.Sprint(time.Now().Unix()), tool.RandomStr(8))
	if err != nil {
		return err
	}
	return d.write(b)
}

func (d defaultResponse) Success() error {
	_, err := d.w.Write([]byte(""))
	return err
}

func (d defaultResponse) Text(context string) error {
	return d.send(NewTextResponseMessage(
		d.c.Request().FromUserName(),
		d.c.Request().ToUserName(),
		context,
	))
}

/************** 结构 ************/
type CDATAString struct {
	CDATA string `xml:",cdata"`
}

type TextResponseMessage struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   CDATAString
	FromUserName CDATAString
	CreateTime   int64
	MsgType      CDATAString
	Content      CDATAString
}

func NewTextResponseMessage(to, from, context string) TextResponseMessage {
	return TextResponseMessage{
		ToUserName:   CDATAString{CDATA: to},
		FromUserName: CDATAString{CDATA: from},
		CreateTime:   time.Now().Unix(),
		MsgType:      CDATAString{CDATA: "text"},
		Content:      CDATAString{CDATA: context},
	}
}
